<?php

use App\Models\User;
use App\Models\Group;
use Intervention\Image\Facades\Image;
use App\Models\Area;
use App\Models\CompanyJobsType;
use App\Models\CamUserResume;
use App\Models\Company;
use Curl\Curl;
use Illuminate\Support\Debug\Dumper;

function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel",
        "amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio",
        "au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-",
        "compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-",
        "go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison",
        "inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5",
        "lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp",
        "mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser",
        "nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips",
        "phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo",
        "samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony",
        "spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-",
        "toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx",
        "wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
    $is_mobile = false;
    foreach ($mobile_agents as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }
    if (stristr($user_agent, 'ipad'))
    {
        $is_mobile = false;
    }
    return $is_mobile;
}

/**
 *
 * id获取充电加油分类名称
 */
if(! function_exists('getUserPerform')) {
    function getUserPerform($year_param,$id)
    {
        $user = \App\Models\UserPerformance::where('year_param',$year_param)->where('user_id',$id)->first();
        if(empty($user))
        {
            $user = new User();
            $user->total = 0;
            return $user;
        }
        else
        {
            return $user;
        }
    }
}


if(! function_exists('getTransferMoney')) {
    function getTransferMoney($money)
    {
        $is_minus = 0;
        if($money < 0){
            $money = $money/-1;
            $is_minus = 1;
        }
        if($money/100000000 > 1){
            $money = round($money/100000000,2);
            if($is_minus == 1){
                return ($money/-1).'亿';
            }else{
                return $money.'亿';
            }
        }
        if($money/1000000 > 1){
            $money = round($money/10000,2);
            if($is_minus == 1){
                return ($money/-1).'万';
            }else{
                return $money.'万';
            }
        }
        if($is_minus == 1){
            return $money/-1;
        }else{
            return $money;
        }
    }
}





/**
 *
 * id获取充电加油标签名称
 */
if(! function_exists('getRefuelTag')) {
    function getRefuelTag($id)
    {
        $user = RefuelTags::find($id);
        if(empty($user))
        {
            return '';
        }
        else
        {
            return $user->name;
        }
    }
}

/**
 *
 * 课程id获取充电加油课程名称
 */
if(! function_exists('getRefuelCourse')) {
    function getRefuelCourse($id)
    {
        $user = RefuelCourse::withTrashed()->find($id);
        if(empty($user))
        {
            return '';
        }
        else
        {
            return $user;
        }
    }
}

/**
 *
 * 课程id获取收藏
 */
if(! function_exists('getRefuelCollect')) {
    function getRefuelCollect($id,$uid)
    {
        $user = \App\Models\RefuelUserCourse::where('course_id',$id)->where('user_id',$uid)->first();
        if(empty($user))
        {
            return '';
        }
        else
        {
            return $user;
        }
    }
}

/**
 *
 * 课程id获取充电加油课程名称
 */
if(! function_exists('getRefuelStore')) {
    function getRefuelStore($id)
    {
        $user = \App\Models\Store::find($id);
        if(empty($user))
        {
            return '';
        }
        else
        {
            return $user;
        }
    }
}

function mailvali($str)
{
    $str = str_replace("</span>","",$str);
    $str = preg_replace("/<span.*?>/","",$str);
    $str = str_replace("</div>","<br/>",$str);
    $str = preg_replace("/<div.*?>/","",$str);
    $str = str_replace("</p>","<br/>",$str);
    $str = preg_replace("/<p.*?>/","",$str);
    $str = trim($str);
    return $str;
}

function pureword($str)
{
    $str = preg_replace("/<([a-zA-Z]+)[^>]*>/","",$str);
    return $str;
}

function onlyword($str)
{
    $str = htmlspecialchars_decode($str);
    $str = str_replace("&nbsp;","",$str);
    $str = strip_tags($str);
    return $str;
}

/**
 * helpers.php.
 *
 * 工具函数
 *
 *
 */
function admin_url($uri)
{
    return url('admin/' . $uri);
}

/**
 * 管理平台 视图化方法
 * @param string $name
 * @return mixed
 */
function admin_view($name)
{
    $args = func_get_args();
    $args[0] = 'admin.' . $name;

    return call_user_func_array('view', $args);
}

function biz_url($uri)
{
    return url('biz/' . $uri);
}

function biz_view($name)
{
    $args = func_get_args();
    $args[0] = 'business.' . $name;
    
    return call_user_func_array('view', $args);
}

if (! function_exists('toJson')) {
    function toJson ($status,$msg='',$data = array() ,$url='')
    {
        $data = [
            'status' => $status,
            'data'   => $data,
            'msg'    => $msg,
            'url'    => $url
        ];
        
        return response()->json($data);
    }
}

if (! function_exists('numToEng')) {
    function numToEng($value) {
        switch ($value) {
            case 0 :
                return 0;
            case 1:
                return 'A';
            case 2:
                return 'B';
            case 3:
                return 'C';
            case 4:
                return 'D';
            case 5:
                return 'E';
            case 6:
                return 'F';
            case 7:
                return 'G';
            case 8:
                return 'H';
            case 9:
                return 'I';
            case 10:
                return 'J';
        }
    }
}

if (! function_exists('qChsColor')) {
    function qChsColor($value) {
        switch ($value%4) {
            case 0 :
                return '#7bc5e0';
            case 1:
                return '#b1cf73';
            case 2:
                return '#f4c564';
            case 3:
                return '#eb9097';
        }
    }
}

if(! function_exists('gznx_format')){
    function gznx_format($gznx,$gznxArr){
        if(isset($gznxArr[$gznx])){
            $value = $gznxArr[$gznx];
            if(str_contains( $value,"-")){
                $val = explode("-", $value);
                $min = intval( $val[0] );
                $max = intval($val[1]);
                
                return [$min,$max];
            } elseif(intval($value) > 0) {
                return intval($value);
            }
        }
        return 0;
    }
}
/**
 * wangjun @20151125
 * 增加获取用户头像的方法
 */
if(! function_exists('userlogo')) {
    function userlogo($uid)
    {
        $user = User::find($uid);
        if(empty($user) || empty($user->user_logo)){
            $logo = asset('/img/list-demo1.png');
        }else{
            $logo = asset($user->user_logo).'?v='.time();
        }
       return $logo;
    }
}



if(! function_exists('usergroup')) {
    function usergroup($uid)
    {
        if($uid == 0 ){
            return '管理员';
        }
        if($uid < 0 ){
            return '发起人';
        }
        $user = Group::find($uid);
        if(empty($user)){
            $logo = '默认';
        }else{
            $logo = $user->group_name;
        }
        return $logo;
    }
}



if (! function_exists('assethelp')) {
    /**
     * Generate an asset path for the application.
     *
     * @param  string  $path
     * @param  bool    $secure
     * @return string
     */
    function assethelp($path, $secure = null)
    {
        $path1 = parse_url($path);
        $path2 = isset($path1['path'])?$path1['path']:$path;
        if(file_exists(public_path($path2))){
            return app('url')->asset($path, $secure);
        }
        if (Str::startsWith($path, ['#', '//', 'mailto:', 'tel:', 'http://', 'https://'])) {
            return $path;
        }
        $file = 'https://cimo.oss-cn-hangzhou.aliyuncs.com'.'/'.trim($path,'/');
        return $file;

    }
}



if(! function_exists('existOss')) {
    function existOss($path)
    {
        $uri = 'http://cimo.oss-cn-hangzhou.aliyuncs.com'.'/'.trim($path,'/');
        $curl  =  new Curl();
        $curl->get($uri);
        if($curl->httpStatusCode == '200'){
            $curl->close();
            return true;
        }else{
            $curl->close();
            return false;
        }
    
    }
}


if(! function_exists('getIsLeader')) {
    function getIsLeader($uid)
    {
        $user = User::find($uid);
        if(empty($user))
        {
            return 0;
        }
        else
        {
            return $user->is_leader;
        }
    }
}

/**
 * wangjun @20151125
 * 增加获取用户名
 */
if(! function_exists('getUserName')) {
    function getUserName($uid)
    {
        $user = User::find($uid);
        if(empty($user))
        {
            return '';
        }
        else
        {
            return str_limit($user->qw_name,10);
        }
    }
}

if(! function_exists('getGroupName')) {
    function getGroupName($uid)
    {
        if($uid == 0){
            return '我的同事';
        }
        $user = Group::find($uid);
        if(empty($user))
        {
            return '';
        }
        else
        {
            return $user->group_name;
        }
    }
}


if(! function_exists('getCompanyName')) {
    function getCompanyName($id,$cate)
    {
        $user = Company::where('id',$id)->first();
        if(empty($user))
        {
            return '公司不存在';
        }
        else
        {
            if($cate == 1){
                return $user->expire_at;
            }else{
                return $user->name;
            }
            
        }
    }
}

//获取user表信息
if(! function_exists('getComuserName')) {
    function getComuserName($id)
    {
        if($id <= 0){
            return '姓名不存在';
        }
        $user = User::find($id);
        if(empty($user))
        {
            return '姓名不存在';
        }
        else
        {
            return $user->qw_name;
        }
    }
}


//获取register表信息
if(! function_exists('getRegisterName')) {
    function getRegisterName($id)
    {
        if($id <= 0){
            return '姓名不存在';
        }
        $user = \App\Models\Register::find($id);
        if(empty($user))
        {
            return '姓名不存在';
        }
        else
        {
            return $user->name;
        }
    }
}










/**
 * 技能测试试卷名
 */
if (!function_exists('getsxname')) {
    function getsxname($id)
    {
        $exam = Exam::find($id);
        if (empty($exam)) {
            return '';
        } else {
            return $exam->name;
        }
    }
}

if (!function_exists('camgetArea')) {
    function camgetArea($id)
    {
        $exam = Area::find($id);
        if (empty($exam)) {
            return '';
        } else {
            return $exam->title;
        }
    }
}

if (!function_exists('camCompanyname')) {
    function camCompanyname($id)
    {
        $exam = Company::find($id);
        if (empty($exam)) {
            return '';
        } else {
            return $exam->name;
        }
    }
}

if (!function_exists('camCompanylogo')) {
    function camCompanylogo($id)
    {
        $exam = Company::find($id);
        if (empty($exam)) {
            return '';
        } else {
            return asset($exam->logo);
        }
    }
}

if (!function_exists('camCompanyscale')) {
    function camCompanyscale($id)
    {
        $exa = Company::find($id);
        if(empty($exa)){
            return '';
        }
        $exam = \App\Models\CompanyScale::find($exa->scale_id)->pluck('name');
        if (empty($exam)) {
            return '';
        } else {
            return $exam;
        }
    }
}

/**
 * 根据id获取jobstypename
 */
if (!function_exists('getjobtypename')) {
    function getjobtypename($id)
    {
        $exam = CompanyJobsType::find($id);
        if (empty($exam)) {
            return '';
        } else {
            return $exam->name;
        }
    }
}

if(! function_exists('array_elements')){
    function array_elements($keys, $src, $default = FALSE) {
        $return = array();
        if(!is_array($keys)) {
            $keys = array($keys);
        }
        foreach($keys as $key) {
            if(isset($src[$key])) {
                $return[$key] = $src[$key];
            } else {
                $return[$key] = $default;
            }
        }
        return $return;
    }
}

/**
 * 将字符串转换数组
 * @param  $haystack  字符串
 * @param  $neddles 字符串
 */
if(! function_exists('strToArray')){
    function strToArray($haystack,$needles){
        $result = array();
        if(str_contains($haystack,$needles)){

            if(ends_with($haystack, $needles)){
                $haystack = substr($haystack,0,strlen($haystack)-strlen($needles));
            }
            if(str_contains($haystack,$needles)){
                $result = explode($needles,$haystack);
            }else{
                $result = array($haystack);
            }
        }else{
            $result = array($haystack);
        }

        return $result;
    }
}
/**
 * 计算当前用户年龄
 */
if(! function_exists('user_age')){
    function user_age($year,$mounth)
    {
        list($y2,$m2) = explode("-",date("Y-m",time()));
        $age = $y2 - $year;
        if((int)($m2) < (int)($mounth))
            $age -= 1;
            return $age;
    }
}
/**
 * 格式化 分布教程内容
 */
if(! function_exists('stepContent')){
    function stepContent($data)
    {
        $content = array();
        $content_first = strToArray($data, '[title@step]');
        foreach ($content_first as $fkey=>$cfisrt)
        {
            $content_second = strToArray($cfisrt, '[steps]');
            if(count($content_second) == 2)
            {
                $content_array = strToArray($content_second[1], '=@-=-=-=');
                $content_main=array();
                foreach ($content_array as $k=>$carry)
                {
                    $contInfo = strToArray($carry, "[imgages]");
                    if(count($contInfo) == 2)
                    {
                        $contImg = strToArray($contInfo[1], "[img]");
                        $content_main[$k] = array(
                            'name'=>$contInfo[0],
                            'img' => $contImg
                        );
                    }
                    else
                    {
                        $content_main[$k] = array(
                            'name'=>$contInfo[0],
                            'img' => ""
                        );
                    }
                }
                $content[$fkey]=array(
                    'title'=>$content_second[0],
                    'content'=>$content_main
                );
            }
            else
            {
                $content[$fkey]=array(
                    'title'=>$content_second[0],
                    'content'=>array()
                );
            }
        }
        return $content;
    }
}
if(! function_exists('getKeyFromArr')){
    function getKeyFromArr($allTeaches,$stcontent){
        foreach ($allTeaches as $key=>$alt)
        {
            if($alt->id == $stcontent->id)
            {
                return $key+1;
            }
        }
    }
}
if(! function_exists('getCategorys')){
    /**
     * 根据子分类获取父分类以及父分类的同级分类
     * @param number $catid
     * @param bool $samelevel  是否获取同级分类
     * @param bool $ret_depath 是否为一维数组
     * @param string $app
     */
    function getCategorys($catid,$samelevel = FALSE,$ret_depath = TRUE,$app="employ"){
        static $depath = 0;
        if($samelevel == true)
        {
            if($catid > 0)
            {
                $nowCate = Category::where(['cat_id'=>$catid,'app'=>$app])->first();
                $parent_id = $nowCate->pid;
            }
            else
            {
                $parent_id = 0;
            }
        }
        $data = Category::where(['pid'=>$parent_id,'app'=>$app])->get();
        $categorys = array();
        if(!empty($data))
        {
            ++$depath;
            foreach ($data as $key=>$res)
            {
                if($res->cat_id == $catid)
                {
                    $current = 1;
                }
                else
                {
                    $current = 0;
                }
                $categorys[$key] = array(
                    'id'        => $res->cat_id,
                    'name'      => $res->cat_name,
                    'pid'       => $res->pid,
                    'sort'      => $res->display_order,
                    'depath'    => $depath,
                    'current'   => $current
                );
                if($ret_depath == true)
                {

                }
                else
                {
                    $parentup = getCategorys($res->cat_id,$samelevel,$ret_depath,$app);
                    if(!empty($parentup))
                    {
                        $categorys[$key]['parent'] = $parentup;
                    }
                }
            }
            --$depath;
        }
        return $categorys;
    }
}
if(! function_exists('get_rnd_num')){
    function get_rnd_num($len)
    {
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(mt_rand(48, 57));
        }
        return $str;
    }
}
if(! function_exists('jsonformat')){
    function jsonformat($status='200',$msg='没有更多数据',$data=array(),$exts = array())
    {
        $result = array(
            'status'        => $status,
            'msg'           => $msg,
            'data'          => $data,
            'exts'          => $exts
        );
        return response()->json($result);
    }
}
if(! function_exists('office2swf')){
    /**
     * word文档转 swf文件
     * @param  $docurl  word 文档路径
     * @param  $docname 文档名称
     * @param  $docpath 文档路径dd
     * @return multitype:string
     */
    function office2swf($docurl,$docname,$docpath){
        if(file_exists(public_path($docurl)))
        {
            $pdfurl = $docpath.$docname.".pdf";
            $command = 'java -jar /data/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar '
                .public_path($docurl).' '.public_path($pdfurl);
                exec($command);
                if(file_exists(public_path($pdfurl)))
                {
                    $swfurl = $docpath.$docname.".swf";
                    $swfCommand = "pdf2swf -o ".public_path($swfurl)
                    ." -T-z-t-f ".public_path($pdfurl)." -s languagedir=/usr/share/xpdf/ -s flashversion=9";
                    exec($swfCommand);
                    return  array('pdfurl'=>$pdfurl,'swfurl'=>$swfurl);
                }else{
                    return array('pdfurl'=>$pdfurl,'swfurl'=>'');
                }

        }
        return array();
    }
}
if(! function_exists('filter_words')){
    function filter_words($content,$wordstr)
    {
        if(!empty($wordstr)&&!empty($content)){
            $wordarr = explode(',',$wordstr);
            $badword = array_combine($wordarr,array_fill(0,count($wordarr),'*'));
            $content = strtr($content, $badword);
        }
        return $content;
    }
}
if(! function_exists('image_resize')){
    function image_resize($url,$width,$height){
        $basePath = public_path();
        if (file_exists(public_path($url))){
            $image = Image::make(public_path($url));
            $filename = $image->filename;
            $extension = $image->extension;
            //$filepath  = str_replace($basePath."/", "", $image->dirname);
            $filepath  = str_replace($basePath."", "", $image->dirname);
            $smallfile = $filepath."/".$filename."_small.".$extension;
            if(!file_exists(public_path($smallfile)))
            {
                $image->resize($width,$height);
                $image->save(public_path($smallfile));
            }
            $newurl = asset($smallfile);
        }else{
            $newurl = asset('/images/t-nopic.jpg');
        }


        return $newurl;
    }
}
if(! function_exists('password_check')){
    function password_check($password){
        if(strlen($password) >16 || strlen($password) < 7){
            return 1;
        }

        if(preg_match('/^[0-9]{1,16}$/', $password)){
            return 2;
        }
        $score = 2;
        if( preg_match('/[a-z]{1,}/', $password) ){
            ++$score;
        }
        if( preg_match('/[A-Z]{1,}/', $password) ){
            ++$score;
        }
        if( preg_match('/[0-9]{1,}/', $password) ){
            ++$score;
        }
        if(preg_match('/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]+/',$password))
        {
            $score += 2;
        }
        if(preg_match('/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]{3,}/',$password))
        {
            ++$score;
        }
        if(strlen($password) > 10)
        {
            ++$score;
        }
        if($score < 5){
            return 3;
        }
        return 0;
    }
}
if(! function_exists('paiming')){
    function paiming(Exam $exam,$userId,$score)
    {
        $exahs = ExamHistory::where(['exam_id'=>$exam->id])->orderBy('score','desc')->orderBy('created_at','ASC')->get();

        $paimings = ['count'=>0,'index'=>0,'surm'=>0,'score'=>0];
    
        $exahsCount = ExamHistory::where(['exam_id'=>$exam->id])->orderBy('score','desc')->count();
        
        $paimings['count'] = $exahsCount;
        
        foreach ($exahs as $key=>$exah) {
            if ($exah->user_id == $userId && $exah->score == $score) {
                $paimings['index'] = $key+1;
                $paimings['score'] = $exah->score;
            }
        }
        $funck = $paimings['count']  - $paimings['index'];
        if($paimings['score'] == $exam->score){
            $surm = 100;
            $paimings['index'] = 1;
        } else {
            if($paimings['index'] == 1 && $paimings['count'] > 1) {
                $surm = 100;
                $paimings['index'] = 1;
            }elseif($funck == 0 && $paimings['count'] == 1) {
                $surm = 0;
            }elseif($funck == 0 && $paimings['count'] > 1) {
                $surm = 10;
            }elseif($funck == 1 && $paimings['count'] >1) {
                $surm = 10;
            }elseif($funck > 1) {
                $surmC = $funck;
                $surm = round($surmC / $paimings['count'],2) * 100;
            }
            
        }
        $paimings['surm'] = $surm;
        
        return $paimings;
    }


    if (!function_exists('ee')) {
        /**
         * Dump the passed variables and end the script.
         *
         * @param  mixed
         * @return void
         */
        function ee()
        {
            array_map(function ($x) {
                (new Dumper)->dump($x);
            }, func_get_args());
        }
    }



//返回当前年
    if (!function_exists('getCurrentYear')) {
        function getCurrentYear()
        {
            $year = date('Y');
            return $year;
        }
    }

    //返回当前年月
    if (!function_exists('getCurrentYearMonth')) {
        function getCurrentYearMonth()
        {
            $month = date('Ym');
            return $month;
        }
    }




    //判断是否正整数
    function is_positive_int($var){
        $var = trim($var);
        if(preg_match("/^[1-9][0-9]*$/",$var)){
            return true;
        }else{
            return false;
        }
    }

    
}